package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.article.mapper.ApArticleConfigMapper;
import com.usian.article.mapper.ApArticleContentMapper;
import com.usian.article.mapper.ApArticleMapper;
import com.usian.article.service.ArticleInfoService;
import com.usian.model.article.dtos.ArticleInfoDto;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleInfoServiceImpl implements ArticleInfoService {

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {

        Map<String,Object> resultMap =new HashMap<>();
        //1:校验参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查文章信息
        ApArticle apArticle = apArticleMapper.selectOne(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, dto.getArticleId()));
        if(apArticle!=null){
            resultMap.put("article",apArticle);
        }

        //2:config  校验下架、删除
        QueryWrapper<ApArticleConfig> queryWrapper =new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticleConfig::getArticleId,dto.getArticleId());
        List<ApArticleConfig> configList = apArticleConfigMapper.selectList(queryWrapper);

        if(configList.size()>0){
            ApArticleConfig apArticleConfig = configList.get(0);
            resultMap.put("config",apArticleConfig);
            //1:下架   1：删除   true:1  false:0
            if(apArticleConfig.getIsDown() || apArticleConfig.getIsDelete()){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
        }
        //3:根据文章id 查询文章的内容
        List<ApArticleContent> apArticleContentList = apArticleContentMapper.selectList(
                Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getArticleId()));
        if(apArticleContentList.size()>0){
            ApArticleContent apArticleContent = apArticleContentList.get(0);
            resultMap.put("content",apArticleContent);
        }

        return ResponseResult.okResult(resultMap);
    }
}
